package com.msc.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.msc.common.lang.Result;
import com.msc.service.bo.QqAccessTokenBo;
import com.msc.common.lang.dto.QqUserDTO;
import com.msc.common.lang.exception.CiliciliException;
import com.msc.service.AccountService;
import com.msc.service.RedisService;
import com.msc.service.bo.UserInfoBo;
import com.msc.thirdparty.QqProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 骑蜗牛的羊
 * @date 2022/6/7 20:52
 * <p>QQ登录</p>
 */
@Controller
public class QQLoginController {
    @Autowired
    RedisService redisService;
    @Autowired
    private QqProvider qqProvider;

    @Value("${qq.client.id}")
    private String qqClientId;

    @Value("${qq.client.secret}")
    private String qqClientSecret;

    @Value("${qq.redirect.uri}")
    private String qqRedirectUri;
    @Value("${qq.api.unionId}")
    private int getQqUnionId;
    @Autowired
    private AccountService accountService;

    /**
     * @return java.lang.String
     * @Description 访问项目根目录跳转到登录页面
     **/
    @RequestMapping("/")
    public String login() {
        return "login";
    }

    @RequestMapping("/admin")
    public String admin() {
        return "dashboard";
    }

    /**
     * @return void
     * @Description 请求QQ登录
     * @Param [request, response]
     **/
   /* @RequestMapping("/loginByQQ")
    public void loginByQQ(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
            System.out.println("请求QQ登录,开始跳转...");
        } catch (QQConnectException | IOException e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 发起请求QQ登录
     */
    @RequestMapping("/loginByQQ")
    @ResponseBody
    public Result loginByQQ1() {
        String state = UUID.randomUUID().toString().substring(0, 8);
        return Result.succ(MapUtil.builder()
                .put("url", "https://graph.qq.com/oauth2.0/authorize?response_type=code")
                .put("redirect_uri", "http%3A%2F%2Fcilicili.top%2Fqqcalback")
                .put("client_id", "102009021")
                .put("state", state)
                .map()
        );
    }

    @RequestMapping("/QQCallBack")
    public String QQCallBack(HttpServletRequest request, HttpServletResponse response) {
        String qState = request.getParameter("state");
        String code = request.getParameter("code");
        System.out.println("传递过来的states是：" + qState);
        System.out.println("传递过来的code是：" + code);
        try {
            QqAccessTokenBo qqAccessTokenDTO = new QqAccessTokenBo();
            qqAccessTokenDTO.setGrant_type("authorization_code");
            qqAccessTokenDTO.setCode(code);
            qqAccessTokenDTO.setClient_id(qqClientId);
            qqAccessTokenDTO.setClient_secret(qqClientSecret);
            qqAccessTokenDTO.setRedirect_uri(qqRedirectUri);

            String string = qqProvider.getAccessToken(qqAccessTokenDTO);
            String access_token = string.split("&")[0].split("=")[1];
            String openid = qqProvider.getOpenID(access_token);
            QqUserDTO qqUser = qqProvider.getUser(access_token, qqClientId, openid);
            //封装对象
            System.out.println("封装对象，新建记录入参是：" + openid + "qState是：" + qState);
            UserInfoBo userInfoBo = accountService.getUserInfoByQQOpenId(qqUser, openid, qState);
            //将登录信息放到redis中去
//            redisService.saveObjectToValue(qState, userInfoBo);
            //30min过期
            redisService.saveObjectToValueWithExpire(qState, userInfoBo,30);
        } catch (CiliciliException e) {
            e.printStackTrace();
        }
        System.out.println("进入了回调方法");
        //return "forward://index.html";
        // return "redirect:index.html";
        return "redirect:http://www.cilicili.top/";
    }

    //根据前后端约定的qState，去缓存寻找用户信息
    @RequestMapping("/checkoutUserinfo")
    @ResponseBody
    public Result checkoutUserinfo(HttpServletRequest request, HttpServletResponse response) {
        String qState = request.getParameter("qState");
        UserInfoBo userInfoBo = (UserInfoBo) redisService.getObjectByValue(qState);

        if (null == userInfoBo) {
            return Result.succ(null);
        }
        System.out.println("userInfoBo是：" + JSON.toJSONString(userInfoBo));
        response.setHeader("Authorization", userInfoBo.getJwt());
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        String state = UUID.randomUUID().toString().substring(0, 8);
        return Result.succ(MapUtil.builder()
                .put("id", "user.getId()")
                .put("username", userInfoBo.getUsername())
                .put("avatar", userInfoBo.getAvatar())
                .put("email", userInfoBo.getEmail())
                .put("role", userInfoBo.getRole())
                .put("nickname", userInfoBo.getNickname())
                .map()
        );
    }

    /**
     * @return java.lang.String
     * @Description 处理掉QQ网名中的特殊表情
     * @Param [str]
     **/
    public String removeNonBmpUnicode(String str) {
        if (str == null) {
            return null;
        }
        str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
        if ("".equals(str)) {
            str = "($ _ $)";
        }
        return str;
    }
}
